<template>
  <div class="form_item-list_id">
    <input v-if="!is_info" type="hidden" :name="name" :value="value">
    <div v-if="!is_info" class="flex">
      <el-button @click="select">选择</el-button>
      <el-button v-if="more" @click="update_value('');list_data=[];">清除</el-button>
      <el-button v-else @click="update_value('0');list_data=[];">归零</el-button>
      <el-input v-model="this_value" class="max" name="" @change="change_value"></el-input>
<!--      <p class="max">{{value}}</p>-->
    </div>
    <div v-else-if="no_table" class="text-ellipsis" :title="value">{{value}}</div>
    <list v-if="!no_table && !is_list" :data="list_data" :cols="list_cols">
      <template v-slot:action="{row}">
        <el-button size="small" @click="move_up(row)" plain>上移</el-button>
        <el-button size="small" @click="remove_row(row)" type="danger" plain>移除</el-button>
      </template>
    </list>
  </div>
</template>

<script>
import {s94_event} from "@/js/s94_tool.js";
import s94Mjs from "s94-js";
import {field_type, iframe, list_cols, list_handle} from "@/js/tool.js";
import {ajax} from "@/js/api_tool.js";

export default {
  _title_: 'ID单选',
  _can_config_: true,
  _can_form_param_: true,
  _can_where_param_: true,
  name: "list_id",
  props: ['name', 'value', 'config', 'is_info', 'more', 'no_table', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    return {
      need_display: true,
      this_value: this.value,
      list_cols: {},
      list_data: [],
      list_api: '',
      iframe_href: '',
      init_timeout_th: false,
      table: '',
      iframe_path: '',
    }
  },
  methods: {
    select(){
      let app = this;
      app.iframe_href && iframe({
        href: app.iframe_href,
        btns: {
          '确定_primary'(win_app){
            let selected = typeof win_app.get_selected === 'function' ? win_app.get_selected() : (win_app.$refs?.list_url?.selected || []);
            if (app.more){
              let value_arr = app.value_arr;
              s94Mjs.each(selected, function(v){
                if (!~value_arr.indexOf(v.id+'')) {
                  app.list_data.push(v);
                  value_arr.push(v.id);
                }
              })
              app.update_value(value_arr.join(','));
            }else {
              if (selected.length != 1) return app.$message.error('只能选择一个');
              app.list_data = [];
              setTimeout(function (){
                app.list_data = selected;
                app.update_value(selected[0]['id']);
              })
            }
            win_app.__iframe.show = false;
          }
        }
      })
    },
    init(){
      //初始化
      this.list_api = '';
      this.list_cols = [];
      if (!this.config) return;
      this.iframe_href = this.config;
      let u = s94Mjs.url(this.iframe_href);
      let param = s94Mjs.param_decode(u.search.substring(1));
      this.iframe_path = u.pathname.replace(/^\//,'');
      this.table = param.api_table;
      if (!this.table){
        let path_dir = this.iframe_path.split('/').shift();
        switch (path_dir) {
          case 'model_base': case 'model_v2_base': {
            this.table = param['model_name'];
          } break;
          case 'order': {
            this.table = `${param['model_name']}_order`;
          } break;
          default: {
            this.table = path_dir;
          } break;
        }
      }
      this.list_api = `/admin/api/list_id?_table_=${this.table}`;

      if (this.no_table) return;
      let cols = Object.values(list_cols(u.pathname));
      this.list_cols = [{name:'id', label:'ID', width:'60px', fixed:'left'}].concat(cols);
      this.list_cols.push({name:'delete_time', label:'删除时间', width:'165px', type:'datetime', fixed:'right'})
      this.list_cols.push({name:'action', label:'操作', width:'120px', type:'hidden', fixed:'right'})
      if (this.more && !this.is_info){
        this.list_cols[this.list_cols.length-1]['type'] = 'action';
      }
      this.get_list_data();
      this.init_timeout_th = false;
    },
    change_value(v){
      this.update_value(v);
      setTimeout(()=>{this.get_list_data();},5);
    },
    get_list_data(){
      let app = this;
      if (!app.list_api || app.no_table) return;
      if (!this.value || this.value==0) return (app.list_data = []);
      let unique_key = this.list_api+':'+this.value;
      let value_arr = this.value_arr;
      let ids = [];
      app.list_data = value_arr.map((v)=>{
        if (parseInt(v) == v) ids.push(v);
        return {id:v};
      })
      ids = ids.join(',');
      let iframe_path = this.iframe_path;
      ajax({url:this.list_api, data:{'where[id][in]':ids,'order[field:id]':ids}, cache:true, skip_error_handle:true},function(res){
        if (unique_key == app.list_api+':'+app.value){//请求列表数据响应后，如果 list_api 没变化，再修改 list_data
          let list_data = list_handle(iframe_path, res.data.list);
          list_data.forEach((row)=>{
            app.list_data.some(row2=>{
              if (row2.id == row.id) {
                Object.assign(row2, row);
                return true;
              }
            })
          })
        }
        return false
      },()=>{return false;})
    },
    remove_row(row){
      let row_i = -1, row_id = row.id, value_arr = this.value_arr;
      this.list_data.forEach(function (v,i){
        if (v.id == row.id) row_i = i;
      })
      if (row_i !== -1){
        this.list_data.splice(row_i,1);
      }
      let val_i = value_arr.indexOf(row_id+'');
      if (val_i !== -1){
        value_arr.splice(val_i,1);
        this.update_value(value_arr.join(','));
      }
    },
    move_up(row){
      let row_id = s94Mjs.to_string(row.id), prev_id, value_arr = this.value_arr;

      let val_i = value_arr.indexOf(row_id);
      if (val_i<=0) return;
      prev_id = value_arr[val_i-1];
      value_arr[val_i] = prev_id;
      value_arr[val_i-1] = row_id;
      this.update_value(value_arr.join(','));

      let list_i = -1;
      this.list_data.forEach(function (v,i){
        if (v.id == row.id) list_i = i;
      })
      if (list_i <= 0) return ;
      this.list_data[list_i] = this.list_data[list_i-1];
      this.list_data[list_i-1] = row;
    },
    update_value(v){
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5);
      this.$emit('update:value', v);
      this.$emit('change', v);
    },
    after_add(evt){
      if (evt.event_name !== `${this.table}/add`) return;
      let value_arr = this.value_arr;
      let id_str = evt.data.data+'';
      if (!this.more && this.value != id_str){
        this.change_value(id_str);
      }
      if (this.more && !~value_arr.indexOf(id_str)){
        value_arr.push(id_str);
        this.change_value(value_arr.join(','));
      }
    }
  },
  watch: {
    value(){
      this.this_value = this.value;
      if (!this.need_display) return;
      if (this.init_timeout_th) return;
      this.init_timeout_th = setTimeout(()=>{ this.init() },5);
    },
    config(v, oldV){
      if (this.init_timeout_th) return;
      this.init_timeout_th = setTimeout(()=>{ this.init() },5);
    },
    is_info(v, oldV){
      if (this.more && !v){
        this.list_cols[this.list_cols.length-1]['type'] = 'action';
      }
    }
  },
  computed: {
    value_arr(){
      let special_id_map = {};
      let val = s94Mjs.trim(s94Mjs.to_string(this.value)).replace(/`([^`]+)`/g, (m0,m1)=>{
        let i = Object.keys(special_id_map).length;
        let k = `__${i}__`;
        special_id_map[k] = m0;
        return k;
      })
      let res = [];
      (val ? val.split(',') : []).forEach(v=>{
        if (v==='') return ;
        return res.push(parseInt(v) == v ? v : special_id_map[v]);
      });
      return res;
    },
  },
  mounted() {
    this.init();
    s94_event('*/add', (evt)=>{
      console.log(evt, '------------------------list_id---------------------')
      this.after_add(evt);
    })
  },
  unmounted() {
    s94_event('*/add', false);
  }
}
</script>

<style scoped>

</style>